from masonite.controllers import Controller
from masonite.views import View
from masonite.request import Request
from masonite.response import Response
from app.traits.MyControllerTrait import MyControllerTrait
from app.traits.MyModelTrait import MyModelTrait
from app.models.AdminActionLog import AdminActionLog
from app.models.AdminUser import AdminUser


class AdminActionLogController(Controller):
    uri = '/admin/action-log'
    temp = 'admin.action-log'

    def index(self, view: View):
        uri  = self.uri + '/index'
        data = {
            'uri': self.uri,
            'title': MyControllerTrait.get_permission_title(uri),
            'menus': MyControllerTrait.get_menu_nav(uri)
        }
        return view.render(self.temp + ".index", data)

    def show(self, request: Request, response: Response):
        admin_user_account = request.input('admin_user_account')
        created_at = request.input('created_at')
        page = request.input('page', 1)
        limit = request.input('limit', 10)

        table = AdminActionLog.get_table_name()
        where = ''
        order = 'id DESC'

        if len(admin_user_account) > 0:
            # 1,2,3
            ids = ''
            admin_users = AdminUser.where_like('account', "{0}%".format).get()
            for admin_user in admin_users:
                ids += str(admin_user['id']) + ','
            ids = ids.strip(',')
            if len(ids) > 0:
                where += " AND admin_user_id IN({0})".format(ids)

        if len(created_at) > 0:
            where += " AND created_at >= {0}".format(created_at)

        admin_users = AdminUser.get_account()
        total, admin_action_logs = MyModelTrait.search_for_show(table, where, '*', page, limit, order)
        if admin_action_logs is not None:
            for index, admin_action_log in enumerate(admin_action_logs):
                account = '-'
                if admin_action_log['admin_user_id'] in admin_users:
                    account = admin_users[admin_action_log['admin_user_id']]
                admin_action_logs[index]['admin_user_id'] = account
                admin_action_logs[index]['created_at'] = MyControllerTrait.time_format_conversion(admin_action_log['created_at'])

        data = {
            'code': 0,
            'message': 'success',
            'total': total,
            'data': admin_action_logs
        }

        return response.json(data)
